package com.zfei.gfb.controller;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.core.Auth;
import com.zfei.gfb.core.HttpJson;
import com.zfei.gfb.core.LogResult;
import com.zfei.gfb.dao.GfbUserMapper;
import com.zfei.gfb.dao.GfbVillagerMapper;
import com.zfei.gfb.device.AppContext;
import com.zfei.gfb.model.GfbUser;
import com.zfei.gfb.model.GfbVillager;
import com.zfei.gfb.query.GfbUserQuery;
import com.zfei.gfb.query.GfbVillagerQuery;
import com.zfei.gfb.request.*;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Now;
import com.zfei.gfb.vo.GfbUserListVo;
import com.zfei.gfb.vo.GfbUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author
 * @version 1.0
 */
@Api(tags = "管理用户接口")
@RestController
@RequestMapping("/web/user")
public class GfbUserController {

    private static final Logger logger = LoggerFactory.getLogger(GfbUserController.class);

    @Resource
    private GfbUserMapper gfbUserMapper;

    @Resource
    private HttpSession httpSession;

    @Resource
    private GfbVillagerMapper gfbVillagerMapper;


    @ApiOperation(value = "登陆")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbUserVo.class),
    })
    @LogResult
    @HttpJson("/login")
    public Object login(@RequestBody GfbUserLoginRequest gfbUserLoginRequest) {

        gfbUserLoginRequest.check();

        String phone = gfbUserLoginRequest.getPhone();
        String password = gfbUserLoginRequest.getPassword();

        GfbUser record = gfbUserMapper.selectByPhone(phone);

        if (record == null) {
            throw new StatusException(Status.NOT_EXIST, "账户不存在");
        }

        if (record.getStatus() == Const.STATUS_OFF) {
            throw new StatusException(Status.UNAUTHORIZED, "该用户已被禁用");
        }

        if (password.equals(record.getPassword())) {
            logger.info("begin set session");
            httpSession.setAttribute(AppContext.SESSION_WEB_USER, record);
            logger.info("end set session");
        } else {
            throw new StatusException(Status.PASSWORD_ERROR);
        }

        record.setLastTime(Now.millis());
        gfbUserMapper.updateByPrimaryKeySelective(record);
        GfbUserVo vo = Beans.copy(record, GfbUserVo.class);

        return vo;

    }

    @ApiOperation(value = "列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbUserListVo.class),
    })
    @Auth(type = {Const.TOWN_MANAGER, Const.VILLAGE_MANAGER})
    @LogResult
    @HttpJson("/list")
    public Object list(@RequestBody GfbUserQuery query) {
        query.check().build(Now::millis);

        GfbUserListVo result = new GfbUserListVo();
        if (AppContext.getInstance().getType() == Const.VILLAGE_MANAGER) {
            query.setType(Const.GFB_VILLAGE_MANAGER);
        }

        int total = gfbUserMapper.total(query);
        result.setTotal(total);
        if (total == 0) {
            result.setData(Lists.newArrayList());
            return result;
        }

        List<GfbUser> records = gfbUserMapper.listByQuery(query);
        List<GfbUserVo> vos = Beans.copys(records, GfbUserVo.class);
        result.setData(vos);
        return result;

    }

    @ApiOperation(value = "新增")
    @Auth(type = {Const.VILLAGE_MANAGER, Const.TOWN_MANAGER})
    @LogResult
    @HttpJson("/add")
    public Object add(@RequestBody GfbUserAddRequest request) {

        request.checkInsertNull();
        if (AppContext.getInstance().getType() == Const.VILLAGE_MANAGER && request.getType() == Const.TOWN_MANAGER) {
            throw new StatusException(Status.INVALID_ARGUMENT);
        }

        GfbUser user = gfbUserMapper.selectByPhone(request.getPhone());
        if (user != null) {
            throw new StatusException(Status.EXIST);
        }

        GfbUser record = Beans.copy(request, GfbUser.class);
        record.setStatus(Const.STATUS_ON);
        record.setCreateTime(Now.millis());
        record.setUpdateTime(Now.millis());
        record.setCntime(DateUtil.now());

        gfbUserMapper.insertSelective(record);
        return null;
    }

    @ApiOperation(value = "编辑")
    @Auth(type = {Const.VILLAGE_MANAGER, Const.TOWN_MANAGER})
    @LogResult
    @HttpJson("/edit")
    public Object edit(@RequestBody GfbUserEditRequest request) {

        request.checkUpdateNull();

        GfbUser record = gfbUserMapper.selectByPrimaryKey(request.getId());
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }

        if (!record.getPhone().equals(request.getPhone())) {
            GfbUser gfbUser = gfbUserMapper.selectByPhone(request.getPhone());
            if (gfbUser != null) {
                throw new StatusException(Status.EXIST);
            }
        }

        BeanUtils.copyProperties(request, record);
        record.setUpdateTime(Now.millis());

        gfbUserMapper.updateByPrimaryKeySelective(record);

        return null;
    }

    @ApiOperation(value = "删除")
    @Auth(type = {Const.VILLAGE_MANAGER, Const.TOWN_MANAGER})
    @LogResult
    @HttpJson("/del")
    public Object del(@RequestBody GfbDelRequest gfbDelRequest) {
        gfbDelRequest.checkDelNull();
        Integer id = gfbDelRequest.getId();

        GfbUser record = gfbUserMapper.selectByPrimaryKey(id);
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }

        gfbUserMapper.deleteByPrimaryKey(id);
        return null;
    }

    @ApiOperation(value = "村民查询")
    @HttpJson("/query")
    public Object query(@RequestBody GfbQueryRequest queryRequest) {
        queryRequest.checkParam();

        GfbVillagerQuery query = new GfbVillagerQuery();
        query.setName(queryRequest.getName());
        query.setVillagerName(queryRequest.getVillagerName());
        List<GfbVillager> dbVillagers = gfbVillagerMapper.list(query);

        return dbVillagers;
    }


}
